# Create your views here.
from django.conf import settings
import sqlite3
import os
sqlite_name = settings.SQLITE_NAME
if 0:
    conn = sqlite3.connect(sqlite_name)
    conn.isolation_level = None

    cur = conn.cursor()
    records = []
    sql = "select * from category where url = '" + url.decode('gbk') + "'"
    res = c_select(cur, sql, records)
    if not len(records) > 0:
        sql = "insert into category(name, url) \
                           values ('"+hp.title.decode('gbk')+"', '"+url.decode('gbk')+"')"
        conn.execute(sql)

#from django.views.generic.list_detail import object_list
from django.shortcuts import render_to_response
from django.template.context import RequestContext
sqlite_names = [
    #"pic_download_dongman.sqlite",
    #"pic_download_hanguo.sqlite",
    #"pic_download_meinv.sqlite",
    #"pic_download_riben.sqlite",
    sqlite_name,
    ]
    
n_per_page = 10

def index(request, template_name='browser/index.html'):

    records = []
    for db in sqlite_names:
        conn = sqlite3.connect(db)
        conn.isolation_level = None
        cur = conn.cursor()
        sql = "select * from category"
        r = []
        res = c_select(cur, sql, r)
        records.extend(r)
    
    cur_page = 1
    if 'page' in request.GET:
        cur_page = request.GET['page']

    num = len(records)
    page_num = num/n_per_page + (num%n_per_page and 1 or 0)
    page_range = range(1,page_num+1)
    context = {'page_range':page_range,
        'pages':page_num,'page':cur_page}
    get_page_range(context)
    
    return render_to_response(template_name,
        {'items': records[(int(cur_page)-1)*n_per_page:int(cur_page)*n_per_page], 'context_c':context},
        context_instance=RequestContext(request)
    )
#    return object_list(request,
#                       records,
#                       paginate_by=10,
#                       template_name=template_name,
#                       #extra_context=extra_context,
#                       allow_empty=True)
    
def category(request, category, template_name='browser/category.html'):
    records = []
    for db in sqlite_names:
        conn = sqlite3.connect(db)
        conn.isolation_level = None
        cur = conn.cursor()
        sql = "select * from article where category_id='" + category +"'"
        r = []
        res = c_select(cur, sql, r)
        records.extend(r)
    cur_page = 1
    if 'page' in request.GET:
        cur_page = request.GET['page']

    num = len(records)
    page_num = num/n_per_page + (num%n_per_page and 1 or 0)
    page_range = range(1,page_num+1)
    context = {'page_range':page_range,
        'pages':page_num,'page':cur_page}
    get_page_range(context)
    
    return render_to_response(template_name,
        {'items': records[(int(cur_page)-1)*n_per_page:int(cur_page)*n_per_page], 'context_c':context},
        context_instance=RequestContext(request)
    )       
#    return object_list(request,
#                       records,
#                       paginate_by=10,
#                       template_name=template_name,
#                       #extra_context=extra_context,
#                       allow_empty=True)
def article(request, article, template_name='browser/article.html'):
    records = []
    for db in sqlite_names:
        conn = sqlite3.connect(db)
        conn.isolation_level = None
        cur = conn.cursor()
        sql = "select * from pic where article_id='" + article +"'"
        r = []
        res = c_select(cur, sql, r)
        records.extend(r)

#    cur_page = 1
#    if 'page' in request.GET:
#        cur_page = request.GET['page']
#
#    num = len(records)
#    page_num = num/n_per_page + (num%n_per_page and 1 or 0)
#    page_range = range(1,page_num+1)
#    context = {'page_range':page_range,
#        'pages':page_num,'page':cur_page}
#    get_page_range(context)
    for s in range(len(records)):
        # if ext is not a picture, the pic save path haven't cut.
        root, ext = os.path.splitext(records[s]["save_path"])
        if ext in settings.ALL_PIC_EXTS:
            records[s]["save_path"] = records[s]["save_path"][:-4]
    return render_to_response(template_name,
        {
        #'items': records[(int(cur_page)-1)*n_per_page:int(cur_page)*n_per_page]
        'items': records,
        #, 'context_c':context,
         'article':article},
        context_instance=RequestContext(request)
    ) 
#    return object_list(request,
#                       records,
#                       paginate_by=10,
#                       template_name=template_name,
#                       #extra_context=extra_context,
#                       allow_empty=True)

def get_page_range(context):
    # generate omit page_range
    half_num = 4
    num = half_num * 2 + 1
    if 'page_range' in context:
        page_cur = int(context['page'])
        page_range_all = context['page_range']
        page_range = []
        page_num = context['pages']
        has_range_prev = False
        has_range_next = False
        if page_num <= num:
            page_range = page_range_all
        else:
            if page_cur >= 1 and page_cur <= half_num + 1:
                page_range = page_range_all[0:num]
                has_range_prev = False
                has_range_next = True
            if page_cur >= half_num + 2 and page_cur <= page_num - (half_num+1):
                page_range = page_range_all[page_cur-1-half_num:page_cur-1+half_num]
                has_range_prev = True
                has_range_next = True
            if page_cur >= page_num - half_num and page_cur <= page_num:
                page_range = page_range_all[page_num-(num-1):page_num]
                has_range_prev = True
                has_range_next = False
        context.update({"page_range": page_range})
        context.update({"has_range_prev": has_range_prev})
        context.update({"has_range_next": has_range_next})

                        
def c_select(cur, sql, records_map_list):
    cur.execute(sql)
    res = cur.fetchall()
    del records_map_list[:]
    records_map_list.extend([dict(zip([j[0] for j in cur.description], i)) for i in res])
    return res
    